import web
import time
from models_webpy import *


class Tunnel:

    def __init__(self):
        self.host = None

    def GET(self, id):

        #Checking if a tunnel_key was gived
        if id is None or len(id) != 36:
            return ''

        #Fetching tunnel's informations for the requested tunnel key
        results = Host().getByTunnelKey(id)

        for host in results:
            self.host = host

        if self.host:
            #Validating the remote address if authorized_ip specified in database
            if self.host.authorized_ip:
                remote_address = web.ctx.env['REMOTE_ADDR']
                if remote_address != self.host.authorized_ip:
                    error = "The remote IP address was '" + remote_address + "'... didn't match with the authorized address"
                    self.updateLog(error)
                    self.updateStamp()
                    return ''

            #Checking tunnel state...
            if self.host.tunnel_status == 'ON':
                #Tunnel state ON
                self.updateStamp()
                if self.host.gateway_user and self.host.gateway_host and self.host.gateway_port:
                    self.updateLog("The tunnel was ON... tunneling parameters has been send!")
                    return str(self.host.gateway_user) + ":" + str(self.host.gateway_host) + ":" + str(self.host.gateway_port)
                else:
                    #Tunnel state ON but missing parameters
                    msg = "The tunnel was ON but a gateway parameter was missing"
                    self.updateLog(msg)
                    return ''
            else:
                #Tunnel state OFF
                self.updateLog('The tunnel status was OFF')
                self.updateStamp()
                return ''
        else:
            #No result from database
            return ''

    def updateStamp(self):
        #Update lastcheck field in database
        now = time.time()
        self.host.update(lastcheck=now)

    def updateLog(self, msg):
        #Update log field in database
        self.host.update(log=msg)
